package com.pengshiyu.controller;

import com.pengshiyu.service.UserService;
import com.pengshiyu.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/list")
    public String list(ModelMap modelMap) throws IOException {
        List<User> list = userService.list();
        System.out.println(list);
        modelMap.addAttribute("list", list);
        return "/list.jsp";
    }

    @RequestMapping("/detail")
    public String detail(int id, ModelMap modelMap) throws IOException {
        User user = userService.detail(id);

        modelMap.addAttribute("user", user);
        return "/detail.jsp";
    }

    @RequestMapping("/update")
    public String update(int id, ModelMap modelMap) throws IOException {
        User user = userService.detail(id);

        modelMap.addAttribute("title", "修改");
        modelMap.addAttribute("user", user);

        return "/edit.jsp";
    }

    @RequestMapping("/add")
    public String add(ModelMap modelMap) throws IOException {
        User user = new User();

        modelMap.addAttribute("title", "添加");
        modelMap.addAttribute("user", user);
        return "/edit.jsp";
    }

    @RequestMapping("/delete")
    public String delete(int id) throws IOException {
        userService.delete(id);
        return "redirect:list";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(User user, ModelMap modelMap) throws IOException {


        if (user.getId() != 0) {
            userService.update(user);
        } else {
            userService.insert(user);
        }

        return "redirect:detail?id=" + user.getId();
    }
}
